#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XinjiangChangjishiPolicy(BaseTaxPolicySpider):
    name = 'xinjiang_changjishi_policy'
    
    province = '新疆维吾尔自治区'
    city: str = "昌吉回族自治州"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格

    def start_requests(self):
        for source, county, url in [
            ['昌吉回族自治州人民政府', "", "https://www.cj.gov.cn/p1/zfwj.html"],
            ['昌吉回族自治州人民政府', "", "https://www.cj.gov.cn/p1/zfbwj.html"],
            ['昌吉回族自治州发展和改革委员会', "", "https://www.cj.gov.cn/p103/bmwj.html"],
            ['昌吉州科学技术局', "", "https://www.cj.gov.cn/p116/bmwj.html"],
            ['昌吉州工业和信息化局', "", "https://www.cj.gov.cn/p114/bmwj.html"],
            ['昌吉州民政局', "", "https://www.cj.gov.cn/p113/bmwj.html"],
            ['昌吉州财政局', "", "https://www.cj.gov.cn/p118/bmwj.html"],
            ['昌吉州人力资源和社会保障局', "", "https://www.cj.gov.cn/p120/bmwj.html"],
            ['昌吉州自然资源局', "", "https://www.cj.gov.cn/p121/bmwj.html"],
            ['昌吉州农业农村局', "", "https://www.cj.gov.cn/p126/bmwj.html"],
            ['昌吉州商务局', "", "https://www.cj.gov.cn/p129/bmwj.html"],
            ['昌吉州文化体育广播电视和旅游局', "", "https://www.cj.gov.cn/p130/bmwj.html"],
            ['昌吉州退役军人事务局', "", "https://www.cj.gov.cn/p137/bmwj.html"],
            ['昌吉州市场监督管理局', "", "https://www.cj.gov.cn/p134/bmwj.html"],
            ['昌吉州乡村振兴局', "", "https://www.cj.gov.cn/p112/bmwj.html"],
            ['昌吉州供销社', "", "https://www.cj.gov.cn/p140/bmwj.html"],
            ['昌吉州金融工作办公室', "", "https://www.cj.gov.cn/p142/bmwj.html"],
            ['国家税务总局昌吉回族自治州税务局', "", "https://www.cj.gov.cn/p147/bmwj.html"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        total = response.xpath(""".""").re_first(r"total:\s*(\d+)") or response.xpath(""".""").re_first(r"共\s*(\d+)\s*页") or 0
        elem_list = response.xpath(
                "//div//td[@class='title']//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=5] |"
                "//li[@class]/div[@class='zctext']/a[contains(@href, 'htm') or @title]/ancestor::div[string-length(string(.))>=5]")
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath("""./a/@href""").re_first(r"""(.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            # if 'list.shtml' in item['source_url']:
            #     continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = math.ceil(int(total) / 15)
            if pages is None or (pages and not elem_list):
                print('ERROR-ERROR', response.text)
            print(response.url, f"page: {pages}")
            for page_num in range(2, int(pages) + 1):
                url = response.url.replace(".html", f"_{page_num}.html")
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xinjiang_changjishi_policy".split())
